package com.atguigu.gulimall.gulimallauthserver.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauthserver.entity.AccessToken;
import com.atguigu.gulimall.gulimallauthserver.entity.SocialUser;
import com.atguigu.gulimall.gulimallauthserver.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauthserver.utils.HttpUtils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Controller
@RequestMapping("/giteeauth")
public class GiteeAuthController {

    String host = "https://gitee.com";
    String path = "/oauth/token";
    String method = "POST";


    @Autowired
    private MemberFeignService memberFeignService;


    @GetMapping("/success")
    public String success(@RequestParam("code") String code, HttpSession session){


        Map<String,String>  querys = new HashMap<>() ;

        Map<String,String> bodys = new HashMap<>();

        bodys.put("grant_type","authorization_code");
        bodys.put("code",code);
        bodys.put("client_id","a50f3d18a0c28a1326751cfe519031c112b909a75331a0fb3e60fb95344d9dbc");
        bodys.put("redirect_uri","http://auth.gulimall.com/giteeauth/success");
        bodys.put("client_secret","76dd70a6a4a0650463709259a714ab5e0a20cdb0c83f194773cee40b11489587");


        Map<String, String> headers = new HashMap<String, String>();
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String,String> map =new HashMap<>();


        try {
            HttpResponse response = HttpUtils.doPost(host,path,method,headers,querys,bodys);

            response.setHeader("Content-Type", "application/x-www-form-urlencoded");

            StatusLine statusLine = response.getStatusLine();

            int statusCode = statusLine.getStatusCode();



            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                System.out.println("entity对象："+entity);

                String s = EntityUtils.toString(entity);


                AccessToken accessToken = JSON.parseObject(s, AccessToken.class);

                //判断用户是否已经存在

                //获取用户资料
                // https://gitee.com/api/v5/user?access_token=d714098cb10971d4576bd4aea409ab55

                Map<String,String> giteeUserQuery = new HashMap<>();

                giteeUserQuery.put("access_token", accessToken.getAccess_token());

                HttpResponse giteeUser = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "GET", headers, giteeUserQuery);


                if(giteeUser.getStatusLine().getStatusCode()==200){

                    HttpEntity giteeUserEntity = giteeUser.getEntity();


                    String s1 = EntityUtils.toString(giteeUserEntity);

                    System.out.println("SocialUser转换前JSON：" + s1);

                    SocialUser socialUser = JSON.parseObject(s1, SocialUser.class);

                    socialUser.setAccess_token(accessToken.getAccess_token());

                    socialUser.setExpires_in(accessToken.getExpires_in());
                    try{

                        R oauthlogin = memberFeignService.oauthlogin(socialUser);

                        if(oauthlogin.getCode()==0){

                            MemberRespVo member = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                            });

                            log.info("接收到的社交账户："+member);

                            //Session验证方案
                            session.setAttribute("loginUser",member);

                            return "redirect:http://gulimall.com";
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }




            }else {

                return "redirect:http://auth.gulimall.com/login.html";
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("code的值是："+code );

        return "redirect:http://auth.gulimall.com/login.html";


    }

    @GetMapping("/key")
    public String Key(HttpResponse response){


        System.out.println(response);


        return "redirect:http://gulimall.com";

    }

}
